package com.cl.cloud.binlog.parser;

import com.cl.cloud.binlog.constant.EventEntityType;
import com.cl.cloud.binlog.tableMeta.TableMetaEntity;
import com.cl.cloud.binlog.tableMeta.TableMetaFactory;
import com.github.shyiko.mysql.binlog.event.Event;
import com.github.shyiko.mysql.binlog.event.EventType;
import com.github.shyiko.mysql.binlog.event.TableMapEventData;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: liuzijian
 * @time: 2021-12-21 14:53
 */
public class CommonEventParserDispatcher implements EventStrategy {

    private final TableMetaFactory tableMetaFactory;
    private final IEventParser updateParser;
    private final IEventParser insertParser;
    private final IEventParser deleteParser;

    public CommonEventParserDispatcher(TableMetaFactory factory) {
        this.tableMetaFactory = factory;
        this.updateParser = new UpdateEventParser(factory);
        this.insertParser = new InsertEventParser(factory);
        this.deleteParser = new DeleteEventParser(factory);
    }

    @Override
    public List<EventEntity> handle(Event event) {
        if (EventType.TABLE_MAP.equals(event.getHeader().getEventType())) {
            TableMapEventData tableMapEventData = event.getData();
            //table_map事件，要更新下tableMetaFactory中的tableId对应的信息缓存
            TableMetaEntity entity = tableMetaFactory.getTableMetaEntity(
                    tableMapEventData.getTableId(),
                    tableMapEventData.getDatabase(),
                    tableMapEventData.getTable()
            );
        }
        if (EventType.isUpdate(event.getHeader().getEventType())) {
            return updateParser.parse(event);
        } else if (EventType.isWrite(event.getHeader().getEventType())) {
            return insertParser.parse(event);
        } else if (EventType.isDelete(event.getHeader().getEventType())) {
            return deleteParser.parse(event);
        }
        return null;
    }
}
